package com.playball.lottery.frm.buyhall;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.WriterException;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.R;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.bean.APPOfAdvertisingBean;
import com.playball.lottery.fragment.frm.Tab1Fragment;
import com.playball.lottery.nt.animal.AnimalServiceImpl;
import com.playball.lottery.sessions.SessionManager;
import com.playball.lottery.util.DefConstants;
import com.playball.lottery.util.LogoConfig;
import com.playball.lottery.util.OKHttpConstants;
import com.playball.lottery.util.PhoneInfo;
import com.playball.lottery.util.QRCodeUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/3/20.
 */

public class BarCodeActivity  extends BaseActivity implements DefConstants,View.OnClickListener {
    private TextView top_title_back,top_title_bace_info;
    private TextView top_title_info;    // 标题
    private ImageView img_code;
    private Button btn_share;
    PhoneInfo phoneInfo;
    // Session Manager Class
    private SessionManager session;
    private Map<String, String> userDetails;
    private final String murl=Tab1Fragment.mUrl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.barcode_layout);
        session = new SessionManager(getApplicationContext());
        phoneInfo = new PhoneInfo(getApplicationContext());
        userDetails = session.getUserDetails();
        //初始化标题
        initTitle();
        //初始化控件
        initView();
        getcode();
    }
    //初始化标题
    public void initTitle(){
        top_title_back=(TextView)findViewById(R.id.top_title_back);
        top_title_back.setVisibility(View.VISIBLE);
        top_title_back.setOnClickListener(this);
        top_title_info = (TextView)findViewById(R.id.top_title_info);
        top_title_info.setText("推广链接");
    }


    //初始化控件
    public void initView(){
        img_code=(ImageView)findViewById(R.id.img_code);
        btn_share=(Button)findViewById(R.id.btn_share);
        btn_share.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //返回
            case R.id.top_title_back:
                finish();
                break;
//            分享
            case R.id.btn_share:
                startActivity(Intent.createChooser(
                        new Intent(Intent.ACTION_SEND)
                                .setType("text/plain")
                                .putExtra(Intent.EXTRA_TEXT,
                                        "天彩彩票手机购彩客户端购彩方便,数据同步,开奖快速,提款安全,下载地址:http://"+ murl+"/user/register/index.html")
                                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), "分享给您的好友"));
                break;
        }
    }
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(OKHttpConstants.CONNECT_TIMEOUT, TimeUnit.SECONDS)
            .build();

    Call post(String url, String json, Callback callback) {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = client.newCall(request);
        call.enqueue(callback);
        return call;
    }

    public  void getCode(){
        //userDetails.get(session.KEY_USERID)"3C075461B9B0"
        String url ="http://mobile.tcaio2o.com/MobileHandler.ashx?platformVersion=6.0&UserID=ODMw&platformCode=Android&sign=6AC3583C15FEB7B931172E8E6AF71937&appVersion=1.0&cmdName=app_zz&uuid="+phoneInfo.getIme()+"&action=10320&params={}";
        Log.v("",url);
        post(url, "", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseStr = response.body().string();
                    String str = responseStr.replaceAll("<a>\\s*|\t|\r|\n</a>", "").trim();

                    if (str != null) {
                        try {
                            JSONTokener jsonParser = new JSONTokener(str);
                            JSONObject js = (JSONObject) jsonParser.nextValue();
//                            final Map<String, Object> Data=com.playball.lottery.util.ConvertJsonToList.getMap(js.getString("Data"));
                            final  String Data=js.getString("Data");
//                            final  String Data="http://dd.tcaio2o.com/user/register/wap/index.html";

                            if (Data != null) {

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        LogoConfig logoConfig = new LogoConfig();
                                        Bitmap logoBitmap = logoConfig.modifyLogo(
                                                BitmapFactory.decodeResource(getResources(),
                                                        R.drawable.buy_ssqxhlb_list_bg), BitmapFactory
                                                        .decodeResource(getResources(),
                                                                R.drawable.app_icons));
                                        Bitmap codeBitmap = null;
                                        try {
                                            codeBitmap = QRCodeUtil.createCode(Data, logoBitmap);
                                        } catch (WriterException e) {
                                            e.printStackTrace();
                                        }
                                        img_code.setImageBitmap(codeBitmap);
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    // Request not successful
                    throw new IOException("Unexpected code " + response);
                }
            }
        });
    }

    public void getcode() {
        final  String Data="http://"+murl+"/user/register/index.html";
        LogoConfig logoConfig = new LogoConfig();
        Bitmap logoBitmap = logoConfig.modifyLogo(
                BitmapFactory.decodeResource(getResources(),
                        R.drawable.buy_ssqxhlb_list_bg), BitmapFactory
                        .decodeResource(getResources(),
                                R.drawable.app_icons));
        Bitmap codeBitmap = null;
        try {
            codeBitmap = QRCodeUtil.createCode(Data, logoBitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        img_code.setImageBitmap(codeBitmap);
    }


//    //文件存储根目录
//    private String getFileRoot(Context context) {
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            File external = context.getExternalFilesDir(null);
//            if (external != null) {
//                return external.getAbsolutePath();
//            }
//        }
//
//        return context.getFilesDir().getAbsolutePath();
//    }
}
